<template>
  <div class="login-container">
    <div class="login-background">
      <div class="bg-overlay"></div>
    </div>

    <div class="login-card">
      <div v-if="currentView === 'login'" class="login-header">
        <div class="logo-section">
          <el-icon :size="48" class="app-logo">
            <ChatRound />
          </el-icon>
          <h1 class="app-title">E-Talk</h1>
          <p class="app-subtitle">让沟通更简单</p>
        </div>
      </div>

      <!-- 登录表单 -->
      <div v-if="currentView === 'login'" class="login-form">
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large" @submit.prevent="handleLogin">
          <el-form-item prop="email">
            <el-input v-model="loginForm.email" placeholder="请输入邮箱" prefix-icon="User" clearable />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" show-password
              @keyup.enter="handleLogin" />
          </el-form-item>

          <div class="login-options">
            <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
            <el-checkbox v-model="loginForm.autoLogin">自动登录</el-checkbox>
          </div>

          <el-form-item>
            <el-button type="primary" class="login-btn" :loading="loading" @click="handleLogin">
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>

          <div class="login-footer">
            <el-link type="primary" :underline="false" @click="switchToRegister">注册新账号</el-link>
            <el-link type="info" :underline="false">忘记密码？</el-link>
          </div>
        </el-form>
      </div>

      <!-- 注册表单 -->
      <div v-else-if="currentView === 'register'" class="register-form">
        <div class="form-header">
          <h2>注册新账号</h2>
          <p>加入E-Talk，开始您的沟通之旅</p>
        </div>

        <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" size="large"
          @submit.prevent="handleRegister">
          <el-form-item prop="email">
            <el-input v-model="registerForm.email" placeholder="请输入邮箱" prefix-icon="Message" clearable />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
              show-password />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码" prefix-icon="Lock"
              show-password />
          </el-form-item>

          <el-form-item prop="nickname">
            <el-input v-model="registerForm.nickname" placeholder="请输入昵称（可选）" prefix-icon="User" clearable />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="register-btn" :loading="loading" @click="handleRegister">
              {{ loading ? '注册中...' : '注册' }}
            </el-button>
          </el-form-item>

          <div class="register-footer">
            <el-link type="primary" :underline="false" @click="switchToLogin">已有账号？立即登录</el-link>
          </div>
        </el-form>
      </div>

      <!-- 验证码验证表单 -->
      <div v-else-if="currentView === 'verify'" class="verify-form">
        <div class="form-header">
          <h2>邮箱验证</h2>
          <p>验证码已发送至 <strong>{{ registerForm.email }}</strong></p>
        </div>

        <el-form ref="verifyFormRef" :model="verifyForm" :rules="verifyRules" size="large"
          @submit.prevent="handleVerify">
          <el-form-item prop="captcha">
            <el-input v-model="verifyForm.captcha" placeholder="请输入6位验证码" prefix-icon="Key" clearable maxlength="6"
              @keyup.enter="handleVerify" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="verify-btn" :loading="loading" @click="handleVerify">
              {{ loading ? '验证中...' : '验证' }}
            </el-button>
          </el-form-item>

          <div class="verify-footer">
            <el-link type="info" :underline="false" @click="resendCode" :disabled="countdown > 0">
              {{ countdown > 0 ? `${countdown}秒后重新发送` : '重新发送验证码' }}
            </el-link>
            <el-link type="primary" :underline="false" @click="switchToRegister">返回注册</el-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ChatRound } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/counter'
import { LoginNet } from '@/api/LoginNet'
import { AuthRegisterNet } from '@/api/AuthRegisterNet'
import { AuthRegisterVerifyNet } from '@/api/AuthRegisterVerifyNet'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
const verifyFormRef = ref<FormInstance>()
const loading = ref(false)
const currentView = ref<'login' | 'register' | 'verify'>('login')
const countdown = ref(0)

// 登录表单数据
const loginForm = reactive({
  email: '',
  password: '',
  rememberMe: false,
  autoLogin: false
})

// 注册表单数据
const registerForm = reactive({
  email: '',
  password: '',
  confirmPassword: '',
  nickname: ''
})

// 验证表单数据
const verifyForm = reactive({
  captcha: ''
})

// 表单验证规则
const loginRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  nickname: [
    { max: 20, message: '昵称长度不能超过 20 个字符', trigger: 'blur' }
  ]
}

// 验证表单验证规则
const verifyRules: FormRules = {
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码只能是数字', trigger: 'blur' }
  ]
}

// 视图切换函数
const switchToLogin = () => {
  currentView.value = 'login'
  resetForms()
}

const switchToRegister = () => {
  currentView.value = 'register'
  resetForms()
}

const switchToVerify = () => {
  currentView.value = 'verify'
  startCountdown()
}

// 重置表单
const resetForms = () => {
  loginFormRef.value?.resetFields()
  registerFormRef.value?.resetFields()
  verifyFormRef.value?.resetFields()

  Object.assign(loginForm, {
    email: '',
    password: '',
    rememberMe: false,
    autoLogin: false
  })

  Object.assign(registerForm, {
    email: '',
    password: '',
    confirmPassword: '',
    nickname: ''
  })

  Object.assign(verifyForm, {
    captcha: ''
  })
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  const valid = await loginFormRef.value.validate().catch(() => false)
  if (!valid) return

  const params = {
    email: loginForm.email,
    password: loginForm.password,
  }

  try {
    loading.value = true
    const res = await LoginNet(params)
    ElMessage.success('登录成功！')
    console.log(res, 'ressssssss')

    // 保存用户信息到store
    userStore.login({
      email: loginForm.email,
      nickname: res.nickName,
      avatar: res.avatar,
      signature: '',
      status: res.status,
    })
    localStorage.setItem('token', res.token)
    // 跳转到聊天页面
    router.push('/chat')

  } catch (error: any) {
    ElMessage.error(error.message || '登录失败，请检查邮箱或密码！')
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  const valid = await registerFormRef.value.validate().catch(() => false)
  if (!valid) return

  const params = {
    email: registerForm.email,
    password: registerForm.password,
    nickname: registerForm.nickname || registerForm.email.split('@')[0] // 如果没有昵称，使用邮箱前缀
  }

  try {
    loading.value = true
    await AuthRegisterNet(params)
    ElMessage.success('注册请求已发送，请查收邮箱验证码！')
    switchToVerify()
  } catch (error) {
    ElMessage.error((error as Error).message || '注册失败，请重试！')
  } finally {
    loading.value = false
  }
}

// 处理验证
const handleVerify = async () => {
  if (!verifyFormRef.value) return

  const valid = await verifyFormRef.value.validate().catch(() => false)
  if (!valid) return

  const params = {
    email: registerForm.email,
    captcha: verifyForm.captcha
  }

  try {
    loading.value = true
    await AuthRegisterVerifyNet(params)
    ElMessage.success('注册成功！请登录您的账号')
    switchToLogin()
  } catch (error) {
    ElMessage.error((error as Error).message || '验证失败，请检查验证码！')
  } finally {
    loading.value = false
  }
}

// 倒计时相关
let countdownTimer: number | null = null

const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer!)
      countdownTimer = null
    }
  }, 1000)
}

// 重新发送验证码
const resendCode = async () => {
  if (countdown.value > 0) return

  const params = {
    email: registerForm.email,
    password: registerForm.password,
    nickname: registerForm.nickname || registerForm.email.split('@')[0]
  }

  try {
    loading.value = true
    await AuthRegisterNet(params)
    ElMessage.success('验证码已重新发送！')
    startCountdown()
  } catch (error) {
    ElMessage.error((error as Error).message || '发送失败，请重试！')
  } finally {
    loading.value = false
  }
}

// 组件卸载时清理定时器
import { onUnmounted } from 'vue'
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped lang="scss">
.login-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: linear-gradient(135deg, var(--primary-500) 0%, var(--secondary-500) 100%);

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.2) 0%, transparent 50%);
    animation: float 20s ease-in-out infinite;
  }
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

  .bg-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.05);
  }
}

@keyframes float {

  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }

  50% {
    transform: translateY(-20px) rotate(1deg);
  }
}

.login-card {
  position: relative;
  width: 420px;
  max-width: 90vw;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: var(--radius-2xl);
  box-shadow: var(--shadow-2xl);
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: var(--spacing-3xl) var(--spacing-2xl);
  animation: slideUp 0.8s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 10;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(40px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: var(--spacing-2xl);

  .logo-section {
    .app-logo {
      color: var(--primary-500);
      margin-bottom: var(--spacing-md);
      animation: pulse 2s ease-in-out infinite;
      filter: drop-shadow(0 4px 8px rgba(99, 102, 241, 0.3));
    }

    .app-title {
      font-size: var(--text-4xl);
      font-weight: var(--font-bold);
      margin: 0 0 var(--spacing-sm) 0;
      background: linear-gradient(135deg, var(--primary-500) 0%, var(--secondary-500) 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      letter-spacing: -0.02em;
    }

    .app-subtitle {
      font-size: var(--text-sm);
      color: var(--text-secondary);
      margin: 0;
      font-weight: var(--font-medium);
    }
  }
}

@keyframes pulse {

  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.05);
  }
}

.login-form,
.register-form,
.verify-form {
  .form-header {
    text-align: center;
    margin-bottom: var(--spacing-xl);

    h2 {
      font-size: var(--text-xl);
      font-weight: var(--font-bold);
      color: var(--text-primary);
      margin: 0 0 var(--spacing-sm) 0;
    }

    p {
      font-size: var(--text-sm);
      color: var(--text-secondary);
      margin: 0;
    }
  }

  .el-form-item {
    margin-bottom: var(--spacing-lg);

    :deep(.el-input) {
      .el-input__wrapper {
        border-radius: var(--radius-lg);
        border: 1px solid var(--border-light);
        box-shadow: var(--shadow-sm);
        transition: var(--transition-normal);
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);

        &:hover {
          border-color: var(--border-medium);
          box-shadow: var(--shadow-md);
        }

        &.is-focus {
          border-color: var(--primary-500);
          box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }

        .el-input__inner {
          font-size: var(--text-base);
          color: var(--text-primary);

          &::placeholder {
            color: var(--text-tertiary);
          }
        }
      }
    }
  }

  .login-options {
    display: flex;
    justify-content: space-between;
    margin-bottom: var(--spacing-xl);

    .el-checkbox {
      :deep(.el-checkbox__label) {
        font-size: var(--text-sm);
        color: var(--text-secondary);
        font-weight: var(--font-medium);
      }

      :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
        background-color: var(--primary-500);
        border-color: var(--primary-500);
      }
    }
  }

  .login-btn,
  .register-btn,
  .verify-btn {
    width: 100%;
    height: 48px;
    border-radius: var(--radius-lg);
    font-size: var(--text-base);
    font-weight: var(--font-semibold);
    background: linear-gradient(135deg, var(--primary-500) 0%, var(--secondary-500) 100%);
    border: none;
    color: var(--text-inverse);
    transition: var(--transition-normal);
    box-shadow: var(--shadow-md);

    &:hover:not(:disabled) {
      transform: translateY(-2px);
      box-shadow: var(--shadow-xl);
    }

    &:active {
      transform: translateY(0);
    }

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
  }

  .login-footer,
  .register-footer {
    display: flex;
    justify-content: space-between;
    margin-top: var(--spacing-lg);

    .el-link {
      font-size: var(--text-sm);
      font-weight: var(--font-medium);

      &.el-link--primary {
        color: var(--primary-600);
      }

      &.el-link--info {
        color: var(--text-secondary);
      }
    }
  }

  .verify-footer {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: var(--spacing-md);
    margin-top: var(--spacing-lg);

    .el-link {
      font-size: var(--text-sm);
      font-weight: var(--font-medium);

      &.el-link--primary {
        color: var(--primary-600);
      }

      &.el-link--info {
        color: var(--text-secondary);
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
  }
}
</style>
